<?php
namespace control;
//管理员后台-库存分布图

class inventoryDistributionMapClass extends adIndexClass
{
	private const page                   = 'inventoryDistributionMap';
	private const table                  = 'inventory_record';
	private const tableWarehouse         = 'warehouse';
	private const tableWarehousePosition = 'warehouse_position';
	private const tableMaterial          = 'material';
	private const title                  = '库存分布图';

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('inventoryDistributionMap.home.warehouse')   => text(array("name" => "name")),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/*客户列表-查询条件*/
	public function home()
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/*客户列表-查询结果*/
	public function homeSearch()
	{
		//获取查询结果
		$where = search([
			"like" => [
				"name" => $this->post('name'),
			],
			"="    => [
				'coid'  => self::$coid,
				'state' => '启用',
			],
		]);
		$where .= self::getWarehouseSql();
		$css   = '<style>
                    ul.box-ul {padding: 0 20px;margin: 0 auto;display: flex;}
                    li.box-li {width: 300px;align-items: center;text-align: left;float: left;border: 1px solid #eee;margin: 10px 20px;padding: 10px 20px;}
                    p.box-li-title {font-weight: bold;margin-bottom: 20px}
                    .box-li a{float:right}
                </style>';

		$page = $this->page(["table" => self::tableWarehouse, "where" => $where, 'pageNum' => 5, "order" => "time desc"]);
		$html = '<ul class="box-ul">';
		$root = root . 'control/adIndex.html?cla=' . self::page;
		foreach ($page['array'] as $array) {
			$total = static::total([
				'table' => self::tableWarehousePosition,
				'where' => generateWhere([
					'coid'    => self::$coid,
					'orderId' => $array['id'],
				]),
			]);
			$used  = static::total([
				'table' => self::tableWarehousePosition,
				'where' => generateWhere([
						'coid'    => self::$coid,
						'orderId' => $array['id'],
					]) . " AND inventoryRecordId is not Null ",
			]);
			$rate  = $total > 0 ? round($used / $total * 100, 3) . '%' : '';
			$html  .= '<li class="box-li">
						<p class="box-li-title">' . $array['name'] . '</p>
						<p>'.lang('inventoryDistributionMap.homeSearch.warehouse').'：' . warehouseClass::getTypeName($array['typeId']) . '</p>
						<p>'.lang('inventoryDistributionMap.homeSearch.totalPosition').'：' . $total . '</p>
						<p>'.lang('inventoryDistributionMap.homeSearch.usedPosition').'：' . $used . '</p>
						<p>'.lang('inventoryDistributionMap.homeSearch.utilizationRate').'：' . $rate . '</p>
						<p><a href="#" onclick="newIframe(\'' . lang('inventoryDistributionMap.homeSearch.distributionDetails') . "', '" . $root . "&fun=viewWarehouse&waid=" . $array['id'] . '\')" class="spanButton">'.lang('inventoryDistributionMap.homeSearch.see').'</a></p>
					 </li>';
		}
		$html   .= '</ul>';
		$button = '';
		//返回
		$json['html'] = $page['hint'] . $css . $button . "<form name='listForm'>" . space . $html . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

	function viewWarehouse()
	{
		$id      = $this->get('waid');
		$info    = query(self::tableWarehouse, " id = '$id' ", 'name');
		$css     = '<style>
.warehouse-body {margin:0 0 50px 0;}
.warehouse-header{font-size: 16px;line-height: 1.5;margin:20px auto}
.warehouse-header .title {font-weight: 700;margin: 0 10px;}
.warehouse-header img{margin-left: 10px;    margin-top: -4px;}
.area-box {width: 99%;display: flex;border: 1px solid #d7d7d7;border-bottom: none;}
.area-box:last-child{border-bottom: 1px solid #d7d7d7;}
.area-title {width: 120px;text-align: center;align-items: center;align-self: center;box-sizing: border-box;}
.area-body {border-left: 1px solid #d7d7d7;padding: 10px;}
.area-row-box {display: flex;margin: 15px 0;}
.area-row-title {width: 70px;text-align: center;align-items: center;align-self: center;box-sizing: border-box;margin-right: 10px;}
.area-col-box {align-items: center;display: inline-table;}
.area-col-title {text-align: center;}
.area-col-body {display: block;float: left;-ms-writing-mode: tb-lr;-webkit-writing-mode: vertical-lr;writing-mode: vertical-lr;}
span.area-layer-box {width: 100px;height: 25px;border: 1px solid #d7d7d7;margin:0 4px;align-self: center;padding: 2px 2px 2px 2px;box-sizing: border-box;display: inline-block;text-align: center;-ms-writing-mode: lr-tb;-webkit-writing-mode: horizontal-tb;writing-mode: horizontal-tb;border-bottom: none;}
span.area-layer-box:last-child{border-bottom: 1px solid #d7d7d7;}
.inventory-record {-ms-writing-mode: initial;-webkit-writing-mode: initial;writing-mode: initial;position: fixed;margin: 10px;padding: 10px;background: #d7d7d7;max-width: 1100px;height: auto}
.inventory-record p{width: 260px;display: block;float: left;border-bottom: 1px solid #fcf9f9;padding: 5px;}
.inventory-record span {float: left;display: flex;width: 260px;}
.materialTitle{white-space: nowrap;overflow: hidden;text-overflow: ellipsis;display: block;}
.used{background-color: #f59a23;color: #fff;cursor:pointer}
.disable{background-color: #d7d7d7}
.hide{display: none}
</style>';
		$unused  = '<img src="../img/control/warehouse-unused.svg" alt="unused">';
		$disable = '<img src="../img/control/warehouse-disable.svg" alt="disable">';
		$used    = '<img src="../img/control/warehouse-used.svg" alt="used">';
		$html    = '<div class="warehouse-body">
                    <div class="warehouse-header"> <span class="title">' . $info['name'] . '</span>' . $unused . lang('inventoryDistributionMap.viewWarehouse.notUsed') . $used . lang('inventoryDistributionMap.viewWarehouse.used') . $disable . lang('inventoryDistributionMap.viewWarehouse.stop') . '</div>';
		// 先获取区域
		$where = " `coid` = '" . self::$coid . "' AND `orderId` = '$id' ";
		$areas = sqlFind(" SELECT DISTINCT `area` FROM `warehouse_position` WHERE $where ORDER BY area ");
		foreach ($areas as $area) {
			$html .= '<div class="area-box">
                        <div class="area-title">' . $area['area'] .lang('inventoryDistributionMap.viewWarehouse.area') .'</div>
                        <div class="area-body">';
			// 获取排
			$rwhere = $where . " AND `area` = '{$area['area']}' ";
			$rows   = sqlFind(" SELECT DISTINCT `row` FROM `warehouse_position` WHERE  $rwhere ORDER BY `row` ");
			foreach ($rows as $no => $row) {
				$html .= '<div class="area-row-box"><div class="area-row-title">' . ($row['row'] ? $row['row'] . lang('inventoryDistributionMap.viewWarehouse.row') : '') . '</div><div class="area-row-body">';
				// 获取列
				$cwhere = $rwhere . " AND `row` = '{$row['row']}' ";
				$cols   = sqlFind("SELECT DISTINCT `col` FROM `warehouse_position` WHERE $cwhere ORDER BY `col` ");
				foreach ($cols as $col) {
					$html .= ($no === 0) ? '<div class="area-col-box"><div class="area-col-title">' . ($col['col'] ? $col['col'] . lang('inventoryDistributionMap.viewWarehouse.col') : '') . '</div><div class="area-col-body">' : '<div class="area-col-box"><div class="area-col-body">';
					// 获取层
					$lwhere = $cwhere . " AND `col` = '{$col['col']}' ";
					$layers = sqlFind(" SELECT DISTINCT `name`, `layer`, `inventoryRecordId`, `state` FROM `warehouse_position` WHERE $lwhere ORDER BY `layer`  DESC ");
					foreach ($layers as $layer) {
						$recordHtml = '';
						// 展示物料聊信息
						if ($layer['inventoryRecordId']) {
							$ids        = explode(',', $layer['inventoryRecordId']);
							$recordHtml = self::queryMateria($ids);
						}
						$class = $recordHtml ? 'used' : ($layer['state'] == '停用' ? 'disable' : '');
						$html  .= '<span class="area-layer-box ' . $class . '">' . $layer['name'] . '</span>' . $recordHtml;
					}
					$html .= '</div></div>';
				}
				$html .= '</div></div>';
			}
			// 区域
			$html .= '</div></div>';
		}
		$html         .= '</div>';
		$html         .= <<<EOT
<script>
$(document).ready(function() {
    // 当鼠标悬浮在.tooltip-trigger元素上时
    $('span.area-layer-box.used').hover(function(that) {
        const obj = $(this).next('.inventory-record'),
    	  height = $(document).height()
        let pageX = that.pageX,
            pageY = that.pageY
        pageY = (height -  pageY < 150) ? height -  180 : pageY - 30
        obj.show(300).css({
            'top': pageY,
            'left': pageX + 20
        })
        that.stopPropagation()
    }, function() {
        // 隐藏相邻的.tooltip元素
        $(this).next(".inventory-record").css({
	        'top': 0,
	        'left': 0
	    }).hide()
    });
});
</script>
EOT;
		$data['html'] = $css . $html;
		return $this->tab($data);
	}


	/**
	 *  查询物料
	 *
	 * @param $array
	 * @return string
	 */
	public static function queryMateria($array): string
	{
		$string = '';
		foreach ($array as $id) {
			$info = query(self::table, " id = '$id' ");
			if (!$info['id']) {
				continue;
			}
			$material      = query(self::tableMaterial, " id = '$info[materialId]'  ", 'name, model, unit');
			$days          = self::diffDays($info['time'], date('Y-m-d H:i:s'));
			$materialTitle = $material['name'] . $material['model'];
            $stock       = inventoryBalanceClass::inventoryNum($info['materialId'], $info['warehouseId'], $info['positionId'], $info['batch']);
			$string        .= "
			<p data-id='i$id'>
				<span title='$materialTitle' class='materialTitle'>".L('inventoryDistributionMap.queryMateria.name')."：$materialTitle</span>
				<span>".L('inventoryDistributionMap.queryMateria.unit')."：{$material['unit']}</span>
				<span>".L('inventoryDistributionMap.queryMateria.num')."：".self::lostZero($stock,'numPrecision')."</span>
				<span>".L('inventoryDistributionMap.queryMateria.batch')."：{$info['batch']}</span>
				<span>".L('inventoryDistributionMap.queryMateria.time')."：{$info['time']}</span>
				<span>".L('inventoryDistributionMap.queryMateria.storageDays')."：{$days}".L('inventoryDistributionMap.queryMateria.day')."</span>
			</p>";
		}
		return $string ? '<div class="inventory-record hide">' . $string . '</div>' : '';
	}

}
